package top.jiangqiang.examples;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.*;

import java.nio.charset.StandardCharsets;

/**
 * 事务消息
 */
@Slf4j
public class ProducerTransactionMessageExample {

    public static void main(String[] args) throws ClientException {
        final ClientServiceProvider provider = ClientServiceProvider.loadService();

        String topic = "TransactionTopic";
        TransactionChecker checker = messageView -> {
            log.info("Receive transactional message check, message={}", messageView);
            return TransactionResolution.COMMIT;
        };
        final Producer producer = ProducerSingleton.getTransactionalInstance(checker, topic);
        final Transaction transaction = producer.beginTransaction();

        String tag = "yourMessageTagA";
        final Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setTag(tag)
                .setKeys("yourMessageKey-565ef26f5727")
                .setBody("This is a transaction message for Apache RocketMQ".getBytes(StandardCharsets.UTF_8))
                .build();
        try {
            final SendReceipt sendReceipt = producer.send(message, transaction);
            log.info("Send transaction message successfully, messageId={}", sendReceipt.getMessageId());
        } catch (Throwable t) {
            log.error("Failed to send message", t);
            return;
        }
        // Commit the transaction.
        transaction.commit();
        // Or rollback the transaction.
        // transaction.rollback();

        // Close the producer when you don't need it anymore.
        // You could close it manually or add this into the JVM shutdown hook.
        // producer.shutdown();
    }
}
